//
//  AIGirlDiscoverViewController.swift
//  AIGirl
//
//  Created by Rae on 2023/12/22.
//

import UIKit

class AIGirlDiscoverViewController: AIGirlBaseViewController {

    private var navView = AIGirlHomeNavView()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private var pageIndex = 1
    private var dataSource: [AIGirlItemModel] = []
    private var cateSource: [String] = []
    private var label = ""
    private var type = 1
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews {
            navView
            collectionView
        }
        
        navView.leading(0).trailing(0).top(.statusHeight).height(44.0)
        collectionView.leading(0).trailing(0).top(.navi_height).bottom(0)
        
        navView.title = "Discover"
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.itemSize = CGSize(width: (.screenWidth - 30.0)/2, height: 230.0)
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets(top: 0, left: 10.0, bottom: 0, right: 10.0)
        layout.sectionHeadersPinToVisibleBounds = true
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(AIGirlDiscoverItem.self, forCellWithReuseIdentifier: AIGirlDiscoverItem.description())
            v.register(AIGirlDiscoverPicCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: AIGirlDiscoverPicCollectionReusableView.description())
            v.register(AIGirlDiscoverCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: AIGirlDiscoverCollectionReusableView.description())
            v.delegate = self
            v.dataSource = self
        }
        
        collectionView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadFirstPage()
        }
        
        NotificationCenter.default.addObserver(forName: NSNotification.Name("refreshGirls"), object: nil, queue: nil) { [weak self] _ in
            self?.loadPageData()
        }
        
        loadData()
        
        navView.showPreviewClosure = {
            self.animation.animation(show: AIGirlMessagePremiumView())
        }
    }
    
    func loadFirstPage() {
        pageIndex = 1
//        collectionView.resetNoMoreInfo()
        loadPageData()
    }
    
    func loadMoreData() {
        pageIndex += 1
        loadPageData()
    }
        
    private func loadPageData(){
        
        self.request.start(.girlList(num: pageIndex, size: 20, startIndex: 0, type: type, label: label), type: AIGirlListModel.self) { result in
            
            if result.isSuccessful, let model = result.model {
                if self.pageIndex == 1 {
                    self.dataSource.removeAll()
                }
                self.dataSource.append(contentsOf: model.rows)
                self.collectionView.reloadData()
                self.collectionView.refresh_end(model.rows.count < 20)
            }
        }
    }
    
    func loadData(){
        request.start(.findLabels,type: AIGirlDiscoverCateStringModel.self) { [weak self] result in
            if result.isSuccessful, let model = result.model {
                self?.cateSource = model.value
//                self?.collectionView.reloadData()
                self?.loadPageData()
            }
        }
    }
}

extension AIGirlDiscoverViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            return 0
        }else{
            return self.dataSource.count
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if indexPath.section == 1 {
            let detailVC = AIGirlModelDetailViewController()
            detailVC.model = dataSource[indexPath.row]
            detailVC.updateDataClosure = {
//                self.loadPageData()
            }
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if indexPath.section == 1 {
            guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: AIGirlDiscoverItem.description(), for: indexPath) as? AIGirlDiscoverItem else { return UICollectionViewCell() }
            item.model = dataSource[indexPath.row]
            return item
        }else{
            
            return UICollectionViewCell()
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if indexPath.section == 0 {
            if kind == UICollectionView.elementKindSectionHeader {
                let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: AIGirlDiscoverPicCollectionReusableView.description(), for: indexPath) as! AIGirlDiscoverPicCollectionReusableView
                // 根据需要自定义 header
                header.bannerPushClosure = { url in
                    if url.count > 0 {
                        let webVC = AIGirlWebViewController()
                        webVC.urlString = url
                        self.navigationController?.pushViewController(webVC, animated: true)
                    }else{
                        self.animation.animation(show: AIGirlMessagePremiumView())
                    }
                }
                return header
            }
        }else{
            if kind == UICollectionView.elementKindSectionHeader {
                let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: AIGirlDiscoverCollectionReusableView.description(), for: indexPath) as! AIGirlDiscoverCollectionReusableView
                // 根据需要自定义 header
                header.updateDataClosure = { lab in
                    self.label = lab
                    self.loadFirstPage()
                }
                header.updateTypeClosure = { ty in
                    self.type = ty
                    self.label = ""
                    self.loadFirstPage()
                }
            
                header.cateArray = cateSource
                return header
            }
        }
        
        return UICollectionReusableView()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        if section == 0 {
            return CGSize(width: .screenWidth, height: 120)
        }else{
            return CGSize(width: .screenWidth, height: 60)
        }
    }
    
}
